/**
 * @Description: 敏感词汇设置
 * @author 阮荣强
 * @date 2019/11/21 下午17:21
 */
import {
  Button,
  Card,
  Col,
  Divider,
  Form,
  Input,
  List,
  Radio,
  Row,
  Switch,
  Tag,
  Tooltip,
  Typography,
} from 'antd';
import React, { Component, Fragment } from 'react';
import { formatMessage, FormattedMessage } from 'umi/locale';
import Modal from 'drag-modal';
import { requestPromise } from '@/utils/request';
import { getWebPath } from '../../../utils/request';
import uiUtils from '../../../utils/uiUtils';

const { Text } = Typography;
const FormItem = Form.Item;

@Form.create()
class ProhibitWords extends Component {
  constructor(props) {
    super(props);
    this.state = {
      keyWord: [],
      keyWordListLoading: false,
      isOpen: false,
      addBatchModalVisible: false,
      checkModalVisible: false,
      addOkBtnLoading: false,
      switchBtnLoading: false,
    };
    this.getBaseInfo();
  }

  //删除
  handleClose = tag => {
    if (tag !== null && tag !== undefined && tag !== '') {
      requestPromise(`${getWebPath()}sys/config/sensitiveWord/del`, {
        method: 'POST',
        contentType: 'application/x-www-form-urlencoded',
        body: { word: tag },
      }).then(res => {
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          //this.getBaseInfo();
        }
      });
    }
  };

  //关/开启违禁词过滤功能
  handleSwitch = checked => {
    this.setState({ switchBtnLoading: true });
    requestPromise(`${getWebPath()}sys/config/sensitiveWord/switch`, {
      method: 'POST',
      contentType: 'application/x-www-form-urlencoded',
      body: { isOpen: checked },
    }).then(res => {
      if (res && res.code === 0) {
        uiUtils.showMessage(
          formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
          'success'
        );
        this.getBaseInfo();
        this.setState({ switchBtnLoading: false });
      }
    });
  };

  //批量添加
  openAddModal = () => {
    this.setState({ addBatchModalVisible: true });
  };

  save = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setState({ addOkBtnLoading: true });
        const obj = this.props.form.getFieldsValue();
        requestPromise(`${getWebPath()}sys/config/sensitiveWord/add`, {
          method: 'POST',
          contentType: 'application/x-www-form-urlencoded',
          body: { contents: obj.multipleContent, level: obj.level },
        }).then(res => {
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
              'success'
            );
            this.setState({ addBatchModalVisible: false, addOkBtnLoading: false });
            this.getBaseInfo();
          }
        });
      }
    });
  };

  //清空
  clear = () => {
    uiUtils.showConfirm(formatMessage({ id: 'ours.curd.show-alert.confirm-clear' }), () => {
      requestPromise(`${getWebPath()}sys/config/sensitiveWord/delAll`, {
        method: 'POST',
      }).then(res => {
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.getBaseInfo();
        }
      });
    });
  };

  //在线检测
  openCheckModal = () => {
    this.setState({ checkModalVisible: true, contentTest: undefined });
  };

  handleCheckWord = () => {
    this.setState({ addCheckOkBtnLoading: true });
    //检测功能
    const { contentTest, keyWord } = this.state;
    if (contentTest === undefined || contentTest === null || contentTest === '') {
      uiUtils.showMessage('文本不能为空！', 'warning');
    }
    //检测
    const checkResult = [];
    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < keyWord.length; i++) {
      const obj = keyWord[i];
      if (contentTest.indexOf(obj.content) !== -1) {
        checkResult.push(obj);
      }
    }
    console.log(checkResult);
    this.setState({ addCheckOkBtnLoading: false, checkResult });
    uiUtils.showMessage('检测完成', 'success');
  };

  //获取违禁词信息
  getBaseInfo = () => {
    this.setState({ keyWordListLoading: true });
    requestPromise(`${getWebPath('sys/config/sensitiveWord/list')}`, {
      method: 'GET',
    }).then(res => {
      console.log(res);
      if (res && res.code === 0) {
        this.setState({
          keyWord: res.data.sensitiveWord,
          isOpen: res.data.switch,
          keyWordListLoading: false,
        });
      }
    });
  };

  exportsAllToExcel = () => {
    window.location.href = `${getWebPath()}sys/config/sensitiveWord/exportsExcelAll`;
  };

  /**
   * 展示的元素
   * @param item
   * @returns {*}
   */
  getEle = (item, closable) => {
    const tag = item.content;
    const isLongTag = tag.length > 20;
    let tagElem;
    //1:替换；2：禁止；3：审核
    if (item.level === 2) {
      tagElem = (
        <Tag
          color="red"
          closable={closable}
          style={{ marginTop: 10 }}
          key={tag}
          onClose={() => this.handleClose(tag)}
        >
          {isLongTag ? `${tag.slice(0, 20)}...` : tag}
        </Tag>
      );
    } else if (item.level === 3) {
      tagElem = (
        <Tag
          color="orange"
          closable={closable}
          style={{ marginTop: 10 }}
          key={tag}
          onClose={() => this.handleClose(tag)}
        >
          {isLongTag ? `${tag.slice(0, 20)}...` : tag}
        </Tag>
      );
    } else {
      tagElem = (
        <Tag
          color="blue"
          closable={closable}
          style={{ marginTop: 10 }}
          key={tag}
          onClose={() => this.handleClose(tag)}
        >
          {isLongTag ? `${tag.slice(0, 20)}...` : tag}
        </Tag>
      );
    }

    return isLongTag ? (
      <Tooltip style={{ marginTop: 10 }} title={tag} key={tag}>
        {tagElem}
      </Tooltip>
    ) : (
      tagElem
    );
  };

  render() {
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
    };

    const ItemLayout = {
      labelCol: { span: 3 },
      wrapperCol: { span: 20 }, //5+19=24,少一个栅格
    };
    const formItemLayout = {
      labelCol: { span: 3 },
      wrapperCol: { span: 21 }, //5+19=24,少一个栅格
    };
    const colSpanLayout = { md: 24, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 24 }; //col之间的间隔?px
    const {
      form: { getFieldDecorator },
    } = this.props;

    return (
      <Fragment>
        <Card
          bordered
          size="small"
          bodyStyle={{ paddingBottom: 10 }}
          style={{ marginBottom: 20 }}
          title=""
        >
          <div>
            <span>全局违禁词过滤功能：</span>
            <Switch
              loading={this.state.switchBtnLoading}
              checkedChildren="开"
              unCheckedChildren="关"
              checked={this.state.isOpen}
              onChange={checked => {
                this.handleSwitch(checked);
              }}
            />
          </div>
        </Card>
        <Card
          bordered
          size="small"
          bodyStyle={{ paddingBottom: 10 }}
          style={{ marginBottom: 20 }}
          title={
            <Fragment>
              <Button type="primary" icon="plus" onClick={this.openAddModal}>
                <FormattedMessage id="ours.curd.list.addBatch" defaultMessage="批量添加" />
              </Button>
              <Button type="primary" icon="delete" {...style} onClick={this.clear}>
                <FormattedMessage
                  id="ours.curd.list.base-form.have-select-clear"
                  defaultMessage="清空"
                />
              </Button>
              <Button type="primary" icon="check" {...style} onClick={this.openCheckModal}>
                <FormattedMessage id="ours.curd.list.onlinecheck" defaultMessage="在线检测" />
              </Button>
              <Button
                type="primary"
                icon="download"
                loading={this.state.downloadBtnLoading}
                {...style}
                onClick={() => {
                  this.setState({
                    downloadBtnLoading: true,
                  });
                  this.exportsAllToExcel();
                  //这里延迟5s关闭loading
                  setTimeout(() => {
                    this.setState({
                      downloadBtnLoading: false,
                    });
                  }, 1000 * 5);
                }}
              >
                <FormattedMessage id="ours.curd.list.export" defaultMessage="导出" />
              </Button>
              <Divider />
              <div>
                <div>
                  <span>图例：</span>
                  <Tag color="red">禁止</Tag>
                  <Tag color="blue">替换</Tag>
                  <Tag color="orange">审核</Tag>
                </div>
                <div>
                  <div>
                    <Text type="secondary">禁止：表示系统在发现违禁词时会禁止当前的操作；</Text>
                  </div>
                  <div>
                    <Text type="secondary">替换：表示系统在发现违禁词时会将违禁词替换为**</Text>
                  </div>
                  <div>
                    <Text type="secondary">审核：根据业务处理</Text>
                  </div>
                </div>
              </div>
            </Fragment>
          }
        >
          <List
            loading={this.state.keyWordListLoading}
            itemLayout="horizontal"
            dataSource={this.state.keyWord}
            renderItem={item => this.getEle(item, true)}
          />
        </Card>
        <Modal
          title="批量添加"
          destroyOnClose
          visible={this.state.addBatchModalVisible}
          onOk={this.save}
          onCancel={() => {
            this.setState({
              addBatchModalVisible: false,
              addOkBtnLoading: false,
            });
          }}
          width={600}
          okText="保存"
          cancelText="取消"
          okButtonProps={{
            loading: this.state.addOkBtnLoading,
          }}
        >
          <Form layout="horizontal">
            <Row gutter={{ ...rowGutterPxLayout }}>
              <Col {...colSpanLayout}>
                <FormItem
                  label="违禁词："
                  extra="支持多个；以中英文(逗号、分号)、空格、回车分隔。"
                  {...formItemLayout}
                >
                  {getFieldDecorator('multipleContent', {
                    // initialValue: "",
                    rules: [
                      {
                        required: true,
                        message: '必填',
                      },
                      {
                        max: 512,
                        message: '最长512个字符',
                      },
                    ],
                  })(<Input.TextArea maxLength={500} rows={7} placeholder="违禁词" />)}
                </FormItem>
              </Col>
              <Col {...colSpanLayout}>
                <FormItem
                  label="级别："
                  extra="禁止：表示系统在发现违禁词时会禁止当前的操作；替换：表示系统在发现违禁词时会将违禁词替换为**；审核：根据业务"
                  {...formItemLayout}
                >
                  {getFieldDecorator('level', {
                    initialValue: 2,
                    rules: [
                      {
                        required: true,
                        message: '必填',
                      },
                    ],
                  })(
                    <Radio.Group>
                      <Radio value={2}>禁止</Radio>
                      <Radio value={1}>替换</Radio>
                      <Radio disabled value={3}>
                        审核
                      </Radio>
                    </Radio.Group>
                  )}
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Modal>
        <Modal
          title="在线检测"
          destroyOnClose
          visible={this.state.checkModalVisible}
          onOk={this.handleCheckWord}
          onCancel={() => {
            this.setState({
              checkResult: [],
              checkModalVisible: false,
              addCheckOkBtnLoading: false,
            });
          }}
          width={600}
          okText="检测"
          cancelText="取消"
          okButtonProps={{
            loading: this.state.addCheckOkBtnLoading,
          }}
        >
          <Form layout="horizontal">
            <Row gutter={{ ...rowGutterPxLayout }}>
              <Col {...colSpanLayout}>
                <Input.TextArea
                  maxLength={500}
                  rows={6}
                  onChange={event => this.setState({ contentTest: event.target.value })}
                  placeholder="请输入待检测的文本"
                />
              </Col>
              <Col {...colSpanLayout}>
                {this.state.checkResult !== undefined && (
                  <Card
                    bordered
                    size="small"
                    bodyStyle={{ paddingBottom: 10 }}
                    style={{ marginBottom: 20 }}
                    title={
                      <div>
                        <div>
                          <h2>检测结果</h2>
                        </div>
                        <div>
                          <Text style={{ marginTop: 10 }} type="secondary">
                            包涵以下违禁词:
                          </Text>
                        </div>
                      </div>
                    }
                  >
                    <List
                      itemLayout="horizontal"
                      dataSource={this.state.checkResult}
                      renderItem={item => this.getEle(item, false)}
                    />
                  </Card>
                )}
              </Col>
            </Row>
          </Form>
        </Modal>
      </Fragment>
    );
  }
}

export default ProhibitWords;
